// pages/release-service/release-service.js

import { Supply } from '../../models/supply'
import { check } from '../../util/identityCheck'
import { Publish } from '../../models/other'
import areaList from '../../util/area'
const publishModel = new Publish()
const supplyModel = new Supply()
import { RedPacket } from '../../models/redpacket'

let packetModel = new RedPacket()

import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
function getShareId() {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') {
    // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    id: null,
    areaList,
    showPopup: {
      classifyName: false,
      transferWay: false,
      serviceArea: false,
      location: false
    },
    classifyList: [],
    cityList: [
      '全国',
      '河南',
      '广东',
      '江苏',
      '河北',
      '浙江',
      '上海',
      '山东',
      '福建',
      '江西',
      '陕西',
      '湖南',
      '四川',
      '湖北',
      '贵州',
      '安徽',
      '北京',
      '山西',
      '广西',
      '甘肃',
      '辽宁',
      '吉林',
      '重庆',
      '天津',
      '黑龙江',
      '云南',
      '内蒙古',
      '海南',
      '宁夏',
      '西藏',
      '青海',
      '新疆',
      '香港',
      '澳门',
      '台湾'
    ],
    Supply: {
      shareUserId: '',
      avatar: '',
      title: '',
      contactName: '',
      contactPhone: '',
      classifyName: '',
      classifyId: '',
      primaryBusiness: '',
      address: '',
      serviceArea: '',
      productList: [],
      location: '',
      companyIntroduction: '',
      supplierName: ''
    },
    hiddenx: false,
    showRedPacketDialog: false,
    totalMoney: 0
  },

  onShow() {
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'Supply.shareUserId': shareUserId
      })
    }, 1000)
    if (!check()) return
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    if (+options.id) {
      this.getDetail()
    } else {
      this.getDraft()
      this.setData({
        showRedPacketDialog: true
      })
    }
  },

  getDetail() {
    supplyModel.detail(
      {
        id: this.data.id
      },
      (res) => {
        wx.hideLoading()
        this.setData({
          Supply: { productList: [], ...res }
        })
        if (res && res.auditStatus == 2) {
          Dialog.alert({
            title: '审核未通过',
            message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`
          }).then(() => {
            this.setData({
              hiddenx: true
            })
          })
        }
      }
    )
  },

  chooseImage() {
    uploadImg.chooseImg(5, (res) => {
      let imgList = this.data.Supply.shopEnvironmentList
      imgList.push(res)
      this.setData({
        'Supply.shopEnvironmentList': imgList,
        'Supply.shopEnvironment': imgList.join(',')
      })
    })
  },

  chooseLocation() {
    let that = this
    wx.chooseLocation({
      success(res) {
        console.log(res)
        that.setData({
          'Supply.address': res.name
        })
      }
    })
  },

  publish() {
    let Supply = this.data.Supply
    if (!Supply.avatar) {
      wx.showToast({
        title: '请上传封面图片',
        icon: 'none'
      })
      return
    }
    if (!Supply.title) {
      wx.showToast({
        title: '请填写发布标题',
        icon: 'none'
      })
      return
    }
    if (!Supply.classifyName) {
      wx.showToast({
        title: '请选择行业分类',
        icon: 'none'
      })
      return
    }
    if (!Supply.primaryBusiness) {
      wx.showToast({
        title: '请填写主营业务',
        icon: 'none'
      })
      return
    }
    if (!Supply.serviceArea) {
      wx.showToast({
        title: '请选择服务区域',
        icon: 'none'
      })
      return
    }
    if (!Supply.location) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none'
      })
      return
    }
    if (!Supply.address) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return
    }
    if (!Supply.contactName) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return
    }
    if (/^[0-9]*$/.test(Supply.contactName)) {
      wx.showToast({
        title: '联系人不可以是数字',
        icon: 'none'
      })
      return
    }
    if (!Supply.contactPhone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      })
      return
    }
    if (!Supply.supplierName) {
      wx.showToast({
        title: '请填写企业名称',
        icon: 'none'
      })
      return
    }

    if (Supply.contactPhone.includes('*')) {
      delete Supply.contactPhone
    }
    this.removeDraft()
    supplyModel.publish(Supply, (res) => {})
    wx.navigateTo({
      url: `/pages/pay-join/pay-join?type=供应商&data=${JSON.stringify(Supply)}`
    })
  },

  update() {
    let Supply = this.data.Supply
    Dialog.confirm({
      message: '更新后需再次审核\n 是否确认更新？'
    }).then(() => {
      if (Supply.contactPhone.includes('*')) {
        delete Supply.contactPhone
      }
      supplyModel.update(Supply, (res) => {
        Dialog.alert({
          title: '更新成功！',
          message: '平台将在24小时内完成审核，请耐心等待！'
        }).then(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.navigateBack()
            }
          })
        })
      })
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  onReady() {
    this.init()
  },

  inputChange(evevt) {
    let key = `Supply.${evevt.currentTarget.dataset.type}`
    this.setData({
      [key]: evevt.detail
    })
  },

  onDateInput(event) {
    this.setData({
      currentDate: event.detail
    })
  },

  uploadCover() {
    uploadImg.chooseImg(1, (imgUrl) => {
      this.setData({
        'Supply.avatar': imgUrl
      })
    })
  },

  onShowPopup(e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key]: true
    })
  },

  onClosePopup() {
    // 关闭弹窗
    for (let key in this.data.showPopup) {
      key = `showPopup.${key}`
      this.setData({
        [key]: false
      })
    }
  },

  onClassify(e) {
    // 选择行业分类
    const id = this.data.classifyList.filter(
      (item) => item.tagName == e.detail
    )[0].id
    this.setData({
      'Supply.classifyName': e.detail,
      'Supply.classifyId': id
    })
  },

  onServiceArea(e) {
    // 选择服务区域
    this.setData({
      'Supply.serviceArea': e.detail
    })
  },

  getClassifyList() {
    // 获取行业分类
    publishModel.getSupplyClassify({}, (res) => {
      this.setData({
        classifyList: res
      })
    })
  },

  removeImg(e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.Supply.shopEnvironmentList
    imgList.splice(index, 1)
    this.setData({
      'Supply.shopEnvironmentList': imgList,
      'Supply.shopEnvironment': imgList.join(',')
    })
  },

  editGoods(e) {
    const index = e.currentTarget.dataset.index
    let goodsList = this.data.Supply.productList
    goodsList = JSON.stringify(goodsList[index])
    wx.navigateTo({
      url: `/pages/supply-addgoods/supply-addgoods?data=${goodsList}&index=${index}`
    })
  },

  toNewPage(event) {
    let path = event.currentTarget.dataset.path
    if (path == 'supply-addgoods') {
      if (this.data.Supply.productList.length >= 10) {
        wx.showToast({
          title: '最多添加十个产品！',
          icon: 'none'
        })
        return
      }
      wx.navigateTo({
        url: `/pages/${path}/${path}`
      })
    } else {
      wx.navigateTo({
        url: `/pages/${path}/${path}`
      })
    }
  },

  delete() {
    Dialog.confirm({
      message: '删除后信息将不再展示，且不可恢复！\n 是否确认删除？'
    }).then(() => {
      supplyModel.delete(
        {
          id: this.data.id
        },
        (res) => {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      )
    })
  },

  onAreaConfirm(e) {
    const location = e.detail.values
    this.setData({
      'Supply.location': location[0].name + location[1].name + location[2].name,
      'showPopup.location': false
    })
  },

  onAreaCancel(e) {
    this.setData({
      'showPopup.location': false
    })
  },

  saveDraft() {
    wx.setStorageSync('supplyData', this.data.Supply)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const Supply = wx.getStorageSync('supplyData') || this.data.Supply
    this.setData({
      Supply
    })
  },

  closeRedDialog() {
    this.setData({
      showRedPacketDialog: false
    })
  },

  getPacketSize() {
    packetModel.getPacketSize((res) => {
      res.forEach((item) => {
        if (item.modeName == '供应商') {
          this.setData({
            totalMoney: item.totalMoney
          })
        }
      })
    })
  },

  removeDraft() {
    wx.removeStorageSync('supplyData')
  },

  touchmove() {
    // 空函数 防止滚动
  },

  init() {
    this.getClassifyList()
    this.getPacketSize()
  }
})
